import {
    toast
} from '../../../utils/util'
import {
    reportCase
} from '../../api/long-insure'
import global from '../../../utils/global'
import dayjs from 'dayjs'
// import user from '../../../utils/user'

Page({

    // /**
    //  * 页面的初始数据
    //  */
    data: {
        ssq: '',
        isup: true,
        btnisdisabled: true,
        reportDate: '',
        reportTime: '',
        worker: {},
        workerPhone: '',
        reportPhone: '',
        reportAddress: '',
        reportContent: '',
        hurtStatus: '1', // 1是 2不是
        hospitalStatus: '1', // 1是 2不是
        accidentType: '1', // 1意外 2工伤
        temporary: [], // 暂时存储视频图片
        visitHospital: '', // 就诊医院
        nowdate: '',
        startdate: '',
        nowdateTime: '',
        startdateTime: '',
    },
    unique(arr) {
        for (var i = 0; i < arr.length; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) { // 第一个等同于第二个，splice方法删除第二个
                    arr.splice(j, 1)
                    j--
                }
            }
        }
        return arr
    },
    bindPickerAddress(e) {
        console.log(e, 'gsdhuhug')
        this.setData({
            ssq: this.unique(e.detail.value).join('')
        })
    },
    naexpage() {
        this.setData({
            btnisdisabled: false
        })
    },
    closepopup() {
        if (!this.data.btnisdisabled) {
            this.setData({
                isup: false
            })
        }
    },
    onReportDate(event) {
        this.setData({
            reportDate: event.detail.value
        })
    },
    onReportTime(event) {
        this.setData({
            reportTime: event.detail.value
        })
    },
    onSelectPeople() {
        wx.navigateTo({
            url: '/packageLongInsure/pages/worker-list/worker-list?type=radio&date=' + this.data.reportDate,
            events: {
                complete: (data) => {
                    if (data[0]) {
                        this.setData({
                            worker: data[0]
                        })
                    }
                }
            }
        })
    },
    // /**
    //  * 生命周期函数--监听页面加载
    //  */
    onLoad: function (options) {
        this.setData({
            nowdate: dayjs().format('YYYY-YY-DD'),
            nowdateTime: dayjs().format('HH:mm')
        })
        let list = JSON.parse(options.model)
        console.log(list, 'listlistlist')
        console.log(list[0].insurStartTime.split(' '))
        if (list[0]) {
            this.setData({
                worker: list[0],
                startdate: list[0].insurStartTime.split(' ')[0]
            })
        }
        // const eventChannel = this.getOpenerEventChannel()
        // eventChannel.on('init', (data) => {
        //     this.setData({
        //         outDangerPhone: data.phone,
        //         outDangerUserName: data.userName,
        //         comboName: data.comboName,
        //         outDangerDate: data.date,
        //         recordId: data.id,
        //         outDangerUserId: data.userId,
        //         reportPhone: user.phoneNum
        //     })
        // })
    },

    onHurtStatus(event) {
        const {
            type
        } = event.currentTarget.dataset
        this.setData({
            hurtStatus: type
        })
    },
    onHospitalStatus(event) {
        const {
            type
        } = event.currentTarget.dataset
        this.setData({
            hospitalStatus: type
        })
    },
    onAccidentType(event) {
        const {
            type
        } = event.currentTarget.dataset
        this.setData({
            accidentType: type
        })
    },
    // onReportPhoneInput(event){
    //     this.setData({
    //         reportPhone:event.detail.value
    //     })
    // },
    // onDangerPhoneInput(event){
    //     this.setData({
    //         outDangerPhone: event.detail.value
    //     })
    // },
    // onAccidentDetailsInput(event){
    //     this.setData({
    //         accidentDetails:event.detail.value
    //     },()=>{
    //         if(this.data.accidentDetails){
    //             this.setData({
    //                 textSwitch:false
    //             })
    //         }else{
    //             this.setData({
    //                 textSwitch:true
    //             })
    //         }
    //     })
    // },
    async onAddInsurance() {
        // 校验提交内容存在的问题
        if (!this.isCheck()) {
            return
        }
        // 上传文件
        wx.showLoading({
            title: '报案上传中',
            mask: true
        })
        const result = await this.filePush()
        wx.hideLoading()
        const files = []
        result.forEach(item => {
            const url = JSON.parse(item).data.fileUrl
            const size = JSON.parse(item).data.fileSize
            let type = 'photo'
            if (
                /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/i.test(url)
            ) {
                type = 'video'
            }
            files.push({
                fileUrl: url,
                fileType: type,
                fileSize: size
            })
        })

        await reportCase({
            accidentDetails: this.data.reportContent,
            accidentType: this.data.accidentType,
            hurtStatus: this.data.hurtStatus,
            hospitalStatus: this.data.hospitalStatus,
            outDangerDate: this.data.reportDate + ' ' + this.data.reportTime,
            // outDangerDate: this.data.reportDate,
            outDangerPhone: this.data.workerPhone,
            outDangerPlace: this.data.ssq + this.data.reportAddress,
            outDangerUserId: this.data.worker.userId,
            outDangerUserName: this.data.worker.userName,
            visitHospital: this.data.visitHospital,
            params: {
                photos: files
            },
            reportPhone: this.data.reportPhone,
            recordId: this.data.worker.id
        })
        wx.redirectTo({
            url: '/pages/success/success?title=申请成功&content=请等待上级审批&opinion=0&back=home'
        })
    },
    // 检查提交内容
    isCheck() {
        // // 只有上传的文件里有一个视频才可通过
        // const isVideo = false
        // this.data.temporary.forEach(item=>{
        //     if(item.fileType === 'video'){
        //         isVideo = true
        //     }
        // })
        // if(!isVideo){
        //     toast('请至少上传一个视频')
        //     return
        // }
        if (!this.data.reportDate) {
            toast('请填写出险日期')
            return
        }
        if (!this.data.reportTime) {
            toast('请填写出险时间')
            return
        }
        if (!this.data.workerPhone) {
            toast('请填写出险人手机号')
            return
        }
        if (!this.data.reportPhone) {
            toast('请填写报案人手机号')
            return
        }
        if (this.data.temporary.length > 3) {
            toast('最多只支持上传三个')
            return
        }
        if (!this.data.ssq) {
            toast('请填写出险省市区')
            return
        }
        if (!this.data.reportAddress) {
            toast('请填写出险详细地点')
            return
        }
        // visitHospital
        if (!this.data.visitHospital) {
            toast('请填写就诊医院')
            return
        }
        if (!this.data.reportContent) {
            toast('请填写出险经过')
            return
        }
        return true
    },

    // 文件批量上传并保存
    async filePush() {
        const tempFiles = this.data.temporary
        return Promise.all(tempFiles.map((item) => {
            return new Promise((resolve) => {
                wx.uploadFile({
                    url: global.baseUrl + '/api/v1/pay/wesure-report-case/upload',
                    filePath: item.tempFilePath,
                    name: 'file',
                    success(res) {
                        console.log('上传成功', res.data)
                        resolve(res.data)
                    },
                })
            })
        }))
    },
    // 上传图片
    async onUpload() {
        const result = await wx.chooseMedia({
            count: 3,
            // maxDuration: 20,
            sizeType: ['compressed'], // 压缩
        })


        if ((this.data.temporary.length + result.tempFiles.length) > 3) {
            toast('最多上传三个视频或图片')
            return
        }
        for (let i in result.tempFiles) {
            if (result.tempFiles[i].duration > 20) {
                toast('请将视频时长控制在20秒以内')
                return
            }
            if (result.tempFiles[i].fileType === 'video' && result.tempFiles[i].size > 30 * 1024 * 1024) {
                toast('请将视频大小控制在30MB以内')
                return
            }
        }
        result.tempFiles = result.tempFiles.map((item, index) => {
            item.fileType = 'image'
            if (
                /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(item.tempFilePath)
            ) {
                item.fileType = 'video'
            }
            return item
        })

        this.data.temporary.push(...result.tempFiles)
        this.setData({
            temporary: this.data.temporary
        })
    },
    onDeleteFile(event) {
        let {
            index
        } = event.currentTarget.dataset
        this.data.temporary.splice(index, 1)
        this.setData({
            temporary: this.data.temporary
        })
    },
    onPreview(event) {
        const {
            url
        } = event.currentTarget.dataset
        wx.previewImage({
            urls: [url]
        })
    },
    onPlay(event) {
        console.log(event.currentTarget.id)
        // 获取 video 上下文 videoContext 对象
        this.videoContext = wx.createVideoContext(event.currentTarget.id, this)
        // 进入全屏状态
        this.videoContext.requestFullScreen()
        return 0
    },
})